package com.aiex.framework.security.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.aiex.framework.security.bo.LoginUser;
import com.aiex.framework.security.config.SecurityTokenProperties;
import com.aiex.framework.security.service.TokenService;
import com.aiex.framework.web.redis.RedisCache;
import com.aiex.framework.web.utils.AddressUtils;
import com.aiex.framework.web.utils.IpUtils;
import com.aiex.framework.web.utils.ServletUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TokenServiceImpl implements TokenService {

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private SecurityTokenProperties securityTokenProperties;

    @Autowired
    private RedisCache redisCache;

    @Override
    public String genToken(LoginUser loginUser) {
        String token = IdUtil.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);
        Map<String, Object> claims = new HashMap<>();
        claims.put(securityTokenProperties.getLoginUserKey(), token);
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, securityTokenProperties.getSecret())
                .compact();
    }


    @Override
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(securityTokenProperties.getHeader());
        if (StringUtils.isNotEmpty(token) && token.startsWith(securityTokenProperties.getTokenPrefix())) {
            token = token.replace(securityTokenProperties.getTokenPrefix(), "");
        }
        return token;
    }

    @Override
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            try {
                Claims claims = getBody(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(securityTokenProperties.getLoginUserKey());
                String userKey = getTokenKey(uuid);
                return redisCache.getCacheObject(userKey);
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    @Override
    public void verifyToken(String token) {
        Claims body = getBody(token);
        String loginUserKey = (String) body.get(securityTokenProperties.getLoginUserKey());
        LoginUser loginUser = redisCache.getCacheObject(getTokenKey(loginUserKey));
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }

    @Override
    public void verifyToken(HttpServletRequest request) {
        String token = getToken(request);
        verifyToken(token);
    }

    @Override
    public void invalidToken(HttpServletRequest request) {
        String token = getToken(request);
        Claims body = getBody(token);
        String loginUserKey = (String) body.get(securityTokenProperties.getLoginUserKey());
        redisCache.deleteObject(loginUserKey);
    }

    /**
     * 获取token的内容
     * @param token
     * @return
     */
    public Claims getBody(String token){
        return Jwts.parser()
                .setSigningKey(securityTokenProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * token的key
     * @param uuid
     * @return
     */
    private String getTokenKey(String uuid){
        return securityTokenProperties.getLoginUserKey() + uuid;
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + securityTokenProperties.getExpireTime() * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, securityTokenProperties.getExpireTime(), TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOs().getName());
    }


}
